package com.smartstate.dataArchives.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 序列号生成器
 */
public class SerialUtil {
  private StringRedisTemplate stringRedisTemplate;

  public SerialUtil(StringRedisTemplate template) {
    this.stringRedisTemplate = template;
  }

  public String getSerialNumber(String service, String siteNum) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    String dateString = simpleDateFormat.format(new Date());
    String key;
    if (StringUtils.isEmpty(siteNum)) {
      key = String.format("SerialNumber-%s-%s", service, dateString);
    } else {
      key = String.format("SerialNumber-%s-%s-%s", siteNum, service, dateString);
    }

    String values = (String)this.stringRedisTemplate.opsForValue().get(key);
    if (StringUtils.isEmpty(values)) {
      values = "0";
    }

    String number = "0000" + (Integer.parseInt(values) + 1);
    number = number.substring(number.length() - 4);
    this.depositRedis(key, number);
    return dateString + number;
  }

  public String getSerialNumber(String service) {
    return this.getSerialNumber(service, (String)null);
  }

  public String getSiteSerialNumber(String service) {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

    HttpServletRequest request;
    try {
      request = attr.getRequest();
    } catch (Exception var5) {
//      log.error("请求中没有site_num属性,返回普通序列号");
      return this.getSerialNumber(service, (String)null);
    }

    String siteNum = request.getHeader("siteNum");
    return this.getSerialNumber(service, siteNum);
  }

  private void depositRedis(String key, String value) {
    this.stringRedisTemplate.opsForValue().set(key, value);
    this.stringRedisTemplate.expire(key, 1L, TimeUnit.DAYS);
  }
}
